// 代理服务，用于解决CORS问题
export class ProxyService {
    private static instance: ProxyService;
    private localProxyUrl = 'http://localhost:3001';
    private fallbackProxies: string[] = [
        'https://cors-anywhere.herokuapp.com',
        'https://api.allorigins.win/raw?url='
    ];
    private currentProxyIndex = 0;
    private proxyHealthStatus: Map<string, boolean> = new Map();
    private lastHealthCheck = 0;
    private healthCheckInterval = 30000; // 30秒

    private constructor() {
        this.initializeProxyHealth();
    }

    public static getInstance(): ProxyService {
        if (!ProxyService.instance) {
            ProxyService.instance = new ProxyService();
        }
        return ProxyService.instance;
    }

    // 初始化代理健康状态
    private initializeProxyHealth(): void {
        this.proxyHealthStatus.set(this.localProxyUrl, false);
        this.fallbackProxies.forEach(proxy => {
            this.proxyHealthStatus.set(proxy, false);
        });
    }

    // 检查本地代理是否可用
    async checkLocalProxy(): Promise<boolean> {
        try {
            const controller = new AbortController();
            const timeoutId = setTimeout(() => controller.abort(), 3000);
            
            const response = await fetch(`${this.localProxyUrl}/health`, {
                method: 'GET',
                signal: controller.signal
            });
            
            clearTimeout(timeoutId);
            const isHealthy = response.ok;
            this.proxyHealthStatus.set(this.localProxyUrl, isHealthy);
            
            if (isHealthy) {
                console.log('✅ 本地代理服务器可用');
            }
            
            return isHealthy;
        } catch (error) {
            console.warn('❌ 本地代理服务器不可用:', error);
            this.proxyHealthStatus.set(this.localProxyUrl, false);
            return false;
        }
    }

    // 获取最佳可用代理
    async getBestProxy(): Promise<string | null> {
        const now = Date.now();
        
        // 定期检查代理健康状态
        if (now - this.lastHealthCheck > this.healthCheckInterval) {
            await this.performHealthCheck();
            this.lastHealthCheck = now;
        }

        // 优先使用本地代理
        if (this.proxyHealthStatus.get(this.localProxyUrl)) {
            return this.localProxyUrl;
        }

        // 寻找可用的备用代理
        for (const proxy of this.fallbackProxies) {
            if (this.proxyHealthStatus.get(proxy)) {
                return proxy;
            }
        }

        return null;
    }

    // 执行健康检查
    private async performHealthCheck(): Promise<void> {
        console.log('🔍 执行代理健康检查...');
        
        // 检查本地代理
        await this.checkLocalProxy();

        // 检查备用代理（简化检查，避免过多网络请求）
        // 在实际使用中才检查备用代理的可用性
    }

    // 通过代理发送请求
    async proxyFetch(url: string, options: RequestInit): Promise<Response> {
        const bestProxy = await this.getBestProxy();
        
        if (bestProxy === this.localProxyUrl) {
            // 使用本地代理
            return await this.fetchViaLocalProxy(url, options);
        } else if (bestProxy) {
            // 使用备用代理
            return await this.fetchViaFallbackProxy(url, options, bestProxy);
        } else {
            // 没有可用代理，尝试直接请求
            console.warn('⚠️ 没有可用代理，尝试直接请求（可能遇到CORS问题）');
            return await this.fetchDirect(url, options);
        }
    }

    // 通过本地代理发送请求
    private async fetchViaLocalProxy(url: string, options: RequestInit): Promise<Response> {
        console.log('🔄 使用本地代理服务器');
        
        // 本地代理有专门的API端点
        const proxyUrl = `${this.localProxyUrl}/api/chat`;
        
        return await fetch(proxyUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': (options.headers as Record<string, string>)?.['Authorization'] || ''
            },
            body: options.body
        });
    }

    // 通过备用代理发送请求
    private async fetchViaFallbackProxy(url: string, options: RequestInit, proxy: string): Promise<Response> {
        console.log('🔄 使用备用代理:', proxy);
        
        let proxyUrl: string;
        if (proxy.includes('allorigins.win')) {
            // AllOrigins 代理需要特殊格式
            proxyUrl = `${proxy}${encodeURIComponent(url)}`;
        } else {
            // 标准代理格式
            proxyUrl = `${proxy}/${url}`;
        }

        try {
            const response = await fetch(proxyUrl, {
                ...options,
                headers: {
                    ...options.headers,
                    'X-Requested-With': 'XMLHttpRequest',
                    'Origin': window.location.origin
                }
            });

            // 标记代理为可用
            this.proxyHealthStatus.set(proxy, true);
            return response;
        } catch (error) {
            // 标记代理为不可用
            this.proxyHealthStatus.set(proxy, false);
            console.error(`代理 ${proxy} 请求失败:`, error);
            throw error;
        }
    }

    // 直接发送请求（无代理）
    private async fetchDirect(url: string, options: RequestInit): Promise<Response> {
        console.log('🔄 直接请求API（可能遇到CORS问题）');
        
        try {
            return await fetch(url, options);
        } catch (error) {
            console.error('直接请求失败:', error);
            throw new Error('CORS_ERROR: 无法直接访问API，需要代理服务器');
        }
    }

    // 测试代理连接
    async testProxyConnection(): Promise<{
        localProxy: boolean;
        fallbackProxies: { url: string; available: boolean }[];
        recommendation: string;
    }> {
        const localProxyAvailable = await this.checkLocalProxy();
        
        const fallbackResults = await Promise.allSettled(
            this.fallbackProxies.map(async (proxy) => {
                try {
                    const controller = new AbortController();
                    const timeoutId = setTimeout(() => controller.abort(), 5000);
                    
                    // 简单的健康检查
                    const testUrl = proxy.includes('allorigins.win') 
                        ? `${proxy}${encodeURIComponent('https://httpbin.org/get')}`
                        : `${proxy}/https://httpbin.org/get`;
                    
                    const response = await fetch(testUrl, {
                        method: 'GET',
                        signal: controller.signal
                    });
                    
                    clearTimeout(timeoutId);
                    return { url: proxy, available: response.ok };
                } catch {
                    return { url: proxy, available: false };
                }
            })
        );

        const fallbackProxies = fallbackResults.map((result, index) => {
            if (result.status === 'fulfilled') {
                return result.value;
            } else {
                return { url: this.fallbackProxies[index], available: false };
            }
        });

        let recommendation = '';
        if (localProxyAvailable) {
            recommendation = '建议使用本地代理服务器（最佳性能）';
        } else if (fallbackProxies.some(p => p.available)) {
            recommendation = '建议启动本地代理服务器以获得最佳体验';
        } else {
            recommendation = '建议启动本地代理服务器或检查网络连接';
        }

        return {
            localProxy: localProxyAvailable,
            fallbackProxies,
            recommendation
        };
    }

    // 获取代理状态
    getProxyStatus(): {
        currentProxy: string | null;
        localProxyHealth: boolean;
        fallbackProxiesHealth: { url: string; healthy: boolean }[];
        lastHealthCheck: Date;
    } {
        const localProxyHealth = this.proxyHealthStatus.get(this.localProxyUrl) || false;
        const fallbackProxiesHealth = this.fallbackProxies.map(proxy => ({
            url: proxy,
            healthy: this.proxyHealthStatus.get(proxy) || false
        }));

        let currentProxy: string | null = null;
        if (localProxyHealth) {
            currentProxy = this.localProxyUrl;
        } else {
            const healthyFallback = this.fallbackProxies.find(proxy => 
                this.proxyHealthStatus.get(proxy)
            );
            currentProxy = healthyFallback || null;
        }

        return {
            currentProxy,
            localProxyHealth,
            fallbackProxiesHealth,
            lastHealthCheck: new Date(this.lastHealthCheck)
        };
    }

    // 强制刷新代理状态
    async refreshProxyStatus(): Promise<void> {
        this.lastHealthCheck = 0; // 强制重新检查
        await this.performHealthCheck();
    }

    // 设置自定义代理URL
    setCustomProxy(url: string): void {
        if (!this.fallbackProxies.includes(url)) {
            this.fallbackProxies.unshift(url); // 添加到开头，优先使用
            this.proxyHealthStatus.set(url, false); // 初始状态为未知
        }
    }

    // 移除自定义代理
    removeCustomProxy(url: string): void {
        const index = this.fallbackProxies.indexOf(url);
        if (index > -1) {
            this.fallbackProxies.splice(index, 1);
            this.proxyHealthStatus.delete(url);
        }
    }
}

// 导出单例实例
export const proxyService = ProxyService.getInstance();